<template>
	<view class="home">
		<view class="home-top" @click="toTop">
			<view class="logo-box" :style="{top: navBarTop + 'px',height: navBarHeight + 'px'}">
				<image src="../../static/images/logo.svg" class="logo" mode=""></image>
			</view>
			<view class="search" @click.stop="toSearch">
				<input class="uni-input" :showAction="false" :disabled="true" placeholder="输入关键词搜索商品" />
			</view>
		</view>
		<view class="uni-margin-wrap">
			<view class="swiper-bg"></view>
			<swiper class="swiper" circular :indicator-dots="true" :autoplay="true" :interval="4000"
				:duration="500">
				<swiper-item v-for="item in banners" :key="item.id" >
					<img class="swiper-ad" :src="`${item.image}`" alt="" @click="swiperLink(item)"/>
				</swiper-item>
			</swiper>
		</view>
		<view class="cate-box">
			<view class="cate-list" v-for="(item,i) in categories.slice(0, 10)" :key="item.id" @click="toCate(item.id)">
				<image class="cate-list-icon" :src="item.icon" mode=""></image>
				<view class="cate-list-name">
					{{item.name}}
				</view>
			</view>
		</view>
		<view class="squre"></view>
		<view class="index-activity" v-if="ActivityGoods.length > 0">
			<view class="activity-wrap">
				<view class="activity-tit">新人专享</view>
				<view class="activity-more" @click="swiperLink({link: '/activities/newer/index'})">
					<text class="name">更多</text>
					<image class="arrow" src="../../static/images/arrow-r-color.svg" mode=""></image>
				</view>
				<view class="activity-con">
					<view class="activity-list" v-for="item in ActivityGoods.slice(0, 3)" :key="item.id" @click="toDetail(item.goods_id)">
						<image :src="item.thumbnail" class="good-img" mode="scaleToFill"></image>
						<view v-if="item.limit_total <= item.used_qty" class="not-send">
							<image class="warn" src="../../static/images/warn.svg" mode="aspectFill"></image>
							<text class="txt">已抢完</text>
						</view>
						<view class="good-name block">{{item.goods.title}}</view>
						<view class="good-price">¥{{(item.activity_price / 100).toFixed(2)}}</view>
						<view class="good-mount">省￥{{((item.sale_price - item.activity_price) / 100).toFixed(2)}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="ads flex" v-if="home_adverts.length > 0">
			<image @click="swiperLink(home_adverts[0])" class="ads-list big" :src="home_adverts[0].image" mode=""></image>
			<view class="ads-r">
				<image @click="swiperLink(home_adverts[1])" class="ads-list small" :src="home_adverts[1].image" mode=""></image>
				<image @click="swiperLink(home_adverts[2])" class="ads-list small" :src="home_adverts[2].image" mode=""></image>
			</view>
		</view>
		<view class="home-nav-box" :style="{top: `${headHeight}px`}">
			<scroll-view class="home-nav" scroll-x="true" enhanced :show-scrollbar="false">
				<view v-for="(item,i) in navs" :key="item.id" :class="['nav-list', currentCate == i ? 'active':'']" @click="navChange(item, i)">
					<view class="name">{{item.name}}</view>
					<view class="description">{{item.description}}</view>
					<view class="bar"></view>
				</view>
			</scroll-view>
		</view>
		<view class="goods-container">
			<view v-for="item in goods" :key="item.goods.id" class="good-list" @click="toDetail(item.goods.id)">
				<goods-item :item="item" :isLeader="isLeader" :leaderId="leaderId"></goods-item>
			</view>
		</view>​
		<uni-popup ref="popAdvert" type="center" :is-mask-click ="false" @close="closePopAdvert">
			<view class="index-ad" v-if="home_pop_advert">
				<image :src="home_pop_advert.image" class="index-ad-img" mode="widthFix" @click="() => {closePopAdvert(); swiperLink(home_pop_advert);}"></image>
				<image src="../../static/images/close.svg" class="index-ad-close" @click="closePopAdvert"></image>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import { indexAds, indexGoods, indexCate, getHomeData, indexSpecGoods, specCate, activityList } from '../../http/apis.js';
	import {getCurrentInstance, ref, nextTick } from 'vue'
	import {
		onLoad,
		onShow,
		onReachBottom
	} from '@dcloudio/uni-app'
	import { useMutations } from '../../store/hooks/useMutations';
	import { useGetters } from '../../store/hooks/useGetters';
	
	const { proxy } = getCurrentInstance();
	const { $onLaunched } = proxy;
	const banners = ref([]);
	const navs = ref([]); // 推荐分类
	const goods = ref([]);
	const navBarTop = ref(getApp().globalData.statusBarHeight);
	const navBarHeight = ref(getApp().globalData.navBarHeight);
	const categories = ref([]); // 商品分类
	const home_adverts = ref([]); // 分类下的广告
	const navTop = ref(0);
	const headHeight = ref(143);
	const home_pop_advert = ref(null); // 首页弹窗
	const popAdvert = ref(null);
	
	// vuex
	const { isLeader, inviter, carts, leaderId } = useGetters(['isLeader', 'inviter', 'carts', 'leaderId']);
	const { setCartBadge } = useMutations(['setCartBadge']);
	
	onLoad(async () => {
		console.log("----index onLoad")
		const data = uni.getStorageSync("fetched-data")
		const loadDataFromFetched = setPreloadData(data)
		await $onLaunched;
		console.log("------loadDataFromFetched:",loadDataFromFetched)
		if (!loadDataFromFetched) {
			uni.removeStorageSync("fetched-data")
			getHomeData().then(res=>{
				setPreloadData(res)
			}).catch((e) => {
				getAds(1);
				getAds(6);
				getAds(7);
				getCategory();
				getSpecGoods();
				getSpecCate();
			})
		}
	})
	onShow(async () => {
		console.log("----index show")
		setCartBadge();
		await $onLaunched;
		getActivityGoods();
	})
	onReachBottom(() => {
		loadMore()
	})
		
	const setPreloadData = (data) => {
		let loadDataFromFetched = false
		if (data) {
			const homeData = JSON.parse(data)
			if (homeData && homeData.goods && homeData.adverts && homeData.goods_categories) {
				banners.value = homeData.adverts;
				home_adverts.value = homeData.home_adverts;
				if (homeData.home_pop_advert) {
					home_pop_advert.value = homeData.home_pop_advert;
					popAdvert && popAdvert.open();
				}
				
				// 商品分类
				const categories = homeData.goods_categories
				categories.sort((a, b) => a.sort - b.sort)
				categories.value = categories;
				getApp().globalData.categories = categories;
				// 首页推荐分类
				const specs = homeData.goods_specs;
				if (specs.length > 0) {
					specs.sort((a, b) => a.sort - b.sort)
					navs.value = [{id:0, name: '全部', description: '有派好货'}].concat(specs)
				}
				
				goods.value = homeData.goods.data
				nextPage.value = homeData.goods.next_page;
				isLoading.value = false;
				nextTick(() => {
					getRect();
				})
				loadDataFromFetched = true
				uni.removeStorageSync("fetched-data")
			}
		}
		return loadDataFromFetched
	}
	// 广告信息
	const getAds = (id) => {
		indexAds({display: id}).then(res => {
			if (id === 1) {
				banners.value = res;
			} else if (id === 6) {
				if (res && res.length > 0) {
					home_pop_advert.value = res[0];
					popAdvert && popAdvert.open();
				}
			} else if (id === 7) {
				home_adverts.value = res;
			}
		})
	}
	// 商品分类
	const getCategory = () => {
		indexCate().then(res => {
			res.sort((a, b) => a.sort - b.sort)
			categories.value = res;
			getApp().globalData.categories = res;
		})
	}
	// 首页推荐
	const getSpecCate = () => {
		specCate().then(res => {
			if (res.length > 0) {
				res.sort((a, b) => a.sort - b.sort)
				navs.value = [{id:0, name: '全部', description: '有派好货'}].concat(res)
			}
		})
	}
	// 推荐商品
	const isLoading = ref(false);
	const currentPage = ref(1);
	const nextPage = ref(1);
	const category_id  = ref(0);
	const getSpecGoods = () => {
		if (isLoading.value) return;
		isLoading.value = true;
		let params = {
			id: category_id.value,
			page: currentPage.value,
		}
		indexSpecGoods(params).then(res => {
			if (currentPage.value > 1) {
				goods.value = goods.value.concat(res.data)
			} else {
				goods.value = res.data || [];
			}
			nextPage.value = res.next_page;
			isLoading.value = false;
			if (navTop.value === 0) {
				nextTick(() => {
					getRect();
				})
			}
		}).catch(res => {
			isLoading.value = false;
		})
	}
	const loadMore = () => {
		if (currentPage.value < nextPage.value && !isLoading.value) {
			currentPage.value += 1;
			getSpecGoods()
		}
	}
	// 切换分类
	const currentCate = ref(0);
	const navChange = (item, index) => {
		uni.createSelectorQuery().in(proxy).select('.home-nav-box')
		.boundingClientRect(rect => {
			if (index == currentCate.value) return;
			if (rect.top <= headHeight.value + 5) {
				uni.pageScrollTo({
					scrollTop: navTop.value - headHeight.value,
					duration: 0
				})
			}
			currentCate.value = index;
			category_id.value = item.id;
			currentPage.value = 1;
			goods.value = [];
			getSpecGoods();
		}).exec();
	}
	// 跳转
	const toDetail = (id) => {
		uni.navigateTo({
			url: `/pages/goodsDetail/index?id=${id}`
		})
	}
	const swiperLink = (item, type) => { // type 6
		if (item.link) {
			uni.navigateTo({
				url: item.link
			})
		} else {
			uni.showToast({
				icon: 'none',
				title: '暂未开放，敬请期待'
			})
		}
		
	}
	const toSearch = () => {
		uni.navigateTo({
			url: `/pages/search/index`
		})
	}
	const toCate = (id) => {
		getApp().globalData.category_id = id;
		uni.switchTab({
			url: '/pages/category/index'
		})
	}
	// 获取元素位置信息
	const getRect = () => {
		uni.createSelectorQuery().in(proxy).select('.home-nav-box')
		.boundingClientRect(rect => {
			navTop.value = rect.top;
		}).exec();
		uni.createSelectorQuery().in(proxy).select('.home-top')
		.boundingClientRect(rect => {
			headHeight.value = rect.height;
		}).exec()
	}
	// 双击事件监听
	const lTime = ref(0);
	const toTop = () => {
		let cTime = new Date().getTime();
		let lTime = lTime.value;
		lTime.value = cTime;
		if (cTime - lTime < 300) {
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 100
			})
		}
	}
	const closePopAdvert = () => {
		popAdvert && popAdvert.close();
	}
	// 新人活动信息
	const ActivityGoods = ref([]); // 新人活动商品
	const getActivityGoods = () => {
		activityList().then(res => {
			if (res.activity_goods_skus) {
				const skus = res.activity_goods_skus || [];
				const can_buy = skus.filter(item => item.limit_total > item.used_qty);
				const not_buy = skus.filter(item => item.limit_total <= item.used_qty);
				const cl = can_buy.length;
				if (cl > 2) {
					ActivityGoods.value = can_buy;
				} else {
					ActivityGoods.value = can_buy.concat(not_buy.slice(0, 3 - cl))
				}
			} else {
				ActivityGoods.value = [];
			}
		})
	}
</script>

<style lang="scss">
	page {
		::v-deep ::-webkit-scrollbar{
			width: 0;
			height: 0;
			color: transparent;
		}
	}
	.flex {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}
	.arrow {
		width: 12rpx;
		height: 24rpx;
	}
	.home {
		width: 100%;
		min-height: 100vh;
		background: linear-gradient(180deg, #FFFFFF 0%, #F8FAFD 48%, #F8FAFD 90%);
		position: relative;
	}
	.home-top {
		width: 100%;
		position: sticky;
		top: 0;
		z-index: 2;
		padding-top: 182rpx;
		box-sizing: border-box;
		overflow: hidden;
		background: linear-gradient(251deg, #F9D63E 22%, #FBE55C 84%);
		.logo-box {
			width: 100%;
			position: absolute;
			top: 105rpx;
			left: 0;
			z-index: 2;
			padding-left: 25rpx;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			.logo {
				width: 198rpx;
				height: 56rpx;
			}
		}
		.search {
			width: 100%;
			height: 72rpx;
			padding: 0 24rpx;
			box-sizing: border-box;
			position: sticky;
			margin-bottom: 24rpx;
			.uni-input {
				width: 100%;
				height: 72rpx;
				background-color: #fff;
				border-radius: 36rpx;
				padding: 0 40rpx;
				box-sizing: border-box;
			}
		}
	}
	.home-ads {
		width: 100%;
	}
	.uni-margin-wrap {
		width: 100%;
		height: 252rpx;
		padding: 0 24rpx;
		box-sizing: border-box;
		position: relative;
		overflow: hidden;
		.swiper-bg {
			position: absolute;
			left: -118rpx;
			top: -182rpx;
			width: 1012rpx;
			height: 360rpx;
			opacity: 1;
			background: linear-gradient(251deg, #F9D63E 22%, #FBE55C 84%);
			clip-path: ellipse(50% 50% at 50% 50%);
		}
		.swiper {
			width: 100%;
			height: 252rpx;
			.swiper-ad {
				width: 100%;
				height: 252rpx;
				border-radius: 16rpx;
			}
		}
	}
	.cate-box {
		width: 100%;
		padding: 0 24rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		margin-top: 34rpx;
		.cate-list {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			flex: 0 0 20%;
			margin-bottom: 25rpx;
			.cate-list-icon {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
			}
			.cate-list-name {
				color: #2E2E2E;
				font-size: 28rpx;
				text-align: center;
				line-height: 56rpx;
				height: 56rpx;
			}
		}
	}
	.squre {
		width: 100%;
		height: 24rpx;
		background-color: #F3F6F9;
	}
	.ads {
		padding: 28rpx 25rpx 28rpx 25rpx;
		box-sizing: border-box;
		.ads-list {
			border-radius: 12rpx;
			&.big {
				width: 320rpx;
				height: 334rpx;
			}
			&.small {
				width: 368rpx;
				height: 160rpx;
			}
		}
		.ads-r {
			height: 334rpx;
			width: 368rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
		}
	}
	.home-nav-box {
		width: 100%;
		padding: 28rpx 0rpx 0 0rpx;
		box-sizing: border-box;
		position: sticky;
		z-index: 2;
		top: 143px;
		background-color: #FFFFFF;
		.home-nav {
			width: 100%;
			white-space: nowrap;
			.nav-list {
				display: inline-block;
				text-align: center;
				vertical-align: middle;
				width: 25%;
				&:last-child {
					margin-right: 0;
				}
				.name {
					color: #2E2E2E;
					font-size: 32rpx;
					line-height: 36rpx;
					font-weight: bold;
				}
				.description {
					color: #7E7D7E;
					font-size: 28rpx;
					line-height: 32rpx;
					margin-top: 15rpx;
				}
				.bar {
					width: 40rpx;
					height: 4rpx;
					background-color: transparent;
					margin: 20rpx auto 0 auto;
				}
				&.active {
					.name {
						color: #F97028;
					}
					.description {
						color: #F97028;
					}
					.bar {
						background-color: #F97028;
					}
				}
			}
		}
	}
	.goods-container {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		align-content: flex-start;
		min-height: 800px;
		padding: 24rpx 24rpx 20rpx 24rpx;
		box-sizing: border-box;
		.good-list {
			width: 340rpx;
			height: 460rpx;
			margin-bottom: 24rpx;
		}
	}
	.index-ad {
		margin: 0 auto;
		width: 500rpx;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		.index-ad-img {
			width: 100%;
		}
		.index-ad-close {
			width: 60rpx;
			height: 60rpx;
			margin-top: 24rpx;
		}
	}
	.index-activity {
		padding: 8rpx 25rpx 28rpx 25rpx;
		box-sizing: border-box;
		.activity-wrap {
			width: 700rpx;
			height: 452rpx;
			padding: 12rpx 20rpx;
			box-sizing: border-box;
			background: url(https://files.youpaish.com/new-user-activity-index.png) no-repeat;
			background-size: 100% 100%;
			position: relative;
			.activity-tit {
				color: #fff;
				font-size: 32rpx;
				text-align: center;
				line-height: 42rpx;
				height: 45rpx;
			}
			.activity-more {
				width: 130rpx;
				height: 40rpx;
				border-radius: 20rpx;
				background-color: #FFFFFF;
				display: flex;
				justify-content: space-between;
				align-items: center;
				line-height: 40rpx;
				padding: 0 28rpx;
				box-sizing: border-box;
				position: absolute;
				top: 40rpx;
				right: 20rpx;
				.name {
					color: #FF7E20;
					font-size: 28rpx;
				}
			}
			.activity-con {
				width: 100%;
				height: 352rpx;
				background-color: #fff;
				border-radius: 8rpx;
				padding: 10rpx 10rpx;
				box-sizing: border-box;
				display: flex;
				justify-content: space-between;
				margin-top: 30rpx;
				.activity-list {
					width: 202rpx;
					height: 332rpx;
					border: 2rpx solid #ECECEC;
					border-radius: 8rpx;
					position: relative;
					.good-img {
						width: 100%;
						height: 164rpx;
						border-top-left-radius: 8rpx;
						border-top-right-radius: 8rpx;
						margin-bottom: 10rpx;
					}
					.block {
						width: 100%;
						padding: 0rpx 8rpx;
						box-sizing: border-box;
					}
					.good-name {
						height: 64rpx;
						color: #000;
						font-size: 24rpx;
						line-height: 32rpx;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						margin-bottom: 9rpx;
					}
					.good-price {
						color: #fff;
						font-size: 24rpx;
						width: 128rpx;
						height: 32rpx;
						line-height: 32rpx;
						text-align: center;
						background: linear-gradient(180deg, #FF7719 0%, #FF3500 100%);
						margin: 0 auto;
						border-radius: 4rpx;
					}
					.good-mount {
						color: #FF7E20;
						font-size: 20rpx;
						line-height: 32rpx;
						text-align: center;
						margin-top: 5rpx;
					}
					.not-send {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 164rpx;
						border-radius: 16rpx;
						background-color: rgba(0,0,0, .5);
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
						.warn {
							width: 48rpx;
							height: 48rpx;
							margin-bottom: 10rpx;
						}
						.txt {
							color: #ffffff;
							font-size: 28rpx;
						}
					}
				}
			}
			
		}
	}
</style>
